package com.sita.tboard.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.sita.bike.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import butterknife.Bind;
import butterknife.ButterKnife;
import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;

public class TrendsImageDetailFragment extends Fragment {
    private String mImageUrl;
    @Bind(R.id.image)
    ImageView mImageView;
    @Bind(R.id.loading)
    ProgressBar progressBar;
    private PhotoViewAttacher mAttacher;

    public static TrendsImageDetailFragment newInstance(String imageUrl) {
        TrendsImageDetailFragment f = new TrendsImageDetailFragment();
        Bundle args = new Bundle();
        args.putString("url", imageUrl);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageUrl = getArguments() != null ? getArguments().getString("url") : null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.rt_trends_image_detail_fragment, container, false);
        ButterKnife.bind(this, v);

        mAttacher = new PhotoViewAttacher(mImageView);

        mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View arg0, float arg1, float arg2) {
                getActivity().finish();
            }
        });
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        progressBar.setVisibility(View.VISIBLE);

        Picasso.with(getContext().getApplicationContext()).load(mImageUrl)
                .fit()
                .centerInside()
                .into(mImageView, new Callback() {
                    @Override
                    public void onSuccess() {
                        progressBar.setVisibility(View.GONE);
                        mAttacher.update();
                    }

                    @Override
                    public void onError() {
                        mImageView.setImageResource(R.drawable.ic_default_adimage);

                        Toast.makeText(getActivity(), getText(R.string.image_cannot_display), Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }

}
